<template>
  <AdminLayout>
    <el-card class="add-class-card">
      <template #header>
        <div class="card-header">
          <h2>添加班级</h2>
        </div>
      </template>
      
      <el-form 
        :model="classForm" 
        :rules="rules" 
        ref="classFormRef" 
        label-width="120px"
        :disabled="submitting"
        class="class-form"
      >
        <el-form-item label="班级名称" prop="className">
          <el-input 
            v-model="classForm.className" 
            placeholder="请输入班级名称" 
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input 
            v-model="classForm.grade" 
            placeholder="请输入年级，如：2023" 
            maxlength="4"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherId">
          <el-select 
            v-model="classForm.headTeacherId" 
            placeholder="请选择班主任（选填）"
            filterable
            clearable
          >
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.teacherId"
              :label="teacher.teacherName"
              :value="teacher.teacherId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input 
            v-model="classForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入班级描述（选填）" 
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter } from 'vue-router'
import { postJson, get } from '../../utils/api'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()

// 表单引用
const classFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const classForm = reactive({
  className: '',
  grade: '',
  headTeacherId: '',
  description: ''
})

// 教师列表
const teacherList = ref<any[]>([])

// 提交状态
const submitting = ref(false)

// 表单验证规则
const rules = reactive({
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 1, max: 50, message: '班级名称长度在 1 到 50 个字符之间', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '年级格式不正确，应为4位数字', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        const year = parseInt(value)
        const currentYear = new Date().getFullYear()
        if (year < 2000 || year > currentYear + 5) {
          callback(new Error('年级应在2000年到' + (currentYear + 5) + '年之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  headTeacherId: [
    { required: false }
  ],
  description: [
    { 
      required: false, 
      max: 100, 
      message: '班级描述长度不能超过 100 个字符', 
      trigger: 'blur'
    }
  ]
})

// 加载教师列表
const loadTeacherList = async () => {
  try {
    // 假设后端有教师查询接口
    const result = await get('/teacher/query')
    if (result.code === 200) {
      teacherList.value = result.data || []
    } else {
      // 使用模拟数据
      teacherList.value = getMockTeacherData()
    }
  } catch (error) {
    console.error('加载教师列表错误:', error)
    // 使用模拟数据
    teacherList.value = getMockTeacherData()
  }
}

// 模拟教师数据
const getMockTeacherData = () => [
  { teacherId: 1, teacherName: '张老师' },
  { teacherId: 2, teacherName: '李老师' },
  { teacherId: 3, teacherName: '王老师' },
  { teacherId: 4, teacherName: '赵老师' }
]

// 提交表单
const handleSubmit = async () => {
  if (!classFormRef.value) return
  
  try {
    // 表单验证
    await classFormRef.value.validate()
    
    // 设置提交状态
    submitting.value = true
    
    // 准备请求数据
    const submitData = {
      className: classForm.className,
      grade: classForm.grade,
      headTeacherId: classForm.headTeacherId || null,
      description: classForm.description || ''
    }
    
    // 调用后端API添加班级
    const result = await postJson('/class/add', submitData)
    
    // 根据API返回结果处理
    if (result.code === 200) {
      ElMessage.success(result.msg || '添加班级成功')
      // 返回班级列表页面
      router.push('/admin/class/list')
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    if (error !== false) { // 如果不是表单验证失败
      console.error('添加班级失败:', error)
      ElMessage.error('网络错误，请检查后端服务是否正常运行')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 返回班级列表页面
  router.push('/admin/class/list')
}

// 组件挂载时加载教师列表
onMounted(() => {
  loadTeacherList()
})
</script>

<style scoped>
.add-class-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.class-form {
  padding: 20px 0;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.el-form-item__content) {
  min-width: 300px;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-select) {
  width: 100%;
}
</style>